﻿/**
 * Created by Fly on 2016/9/12.
 */
var express = require('express');
var router = express.Router();
var filter=require('../util/filter');
var articleDAO=require('../dao/articleDAO');
var formidable=require('formidable');
var fs=require('fs');
/* GET users listing. */
router.get('/', function(req, res) {
        delete req.session.userID;
        res.redirect('/');

});
router.post('/', function(req, res){

        var form=new formidable.IncomingForm();

        form.uploadDir="../public/upload/";

        form.parse(req,function(err,fields,files){
                if(err){
                        res.locals.error=err;
                        return;
                }
                var extName='';//后缀名
                switch(files.fileImage01.type){
                        case 'image/jpeg':
                                extName='jpeg';
                                break;
                        case 'image/jpg':
                                extName='jpg';
                                break;
                        case 'image/png':
                                extName='png';
                                break;
                        case 'image/x-png':
                                extName='png';
                                break;
                }
                if(extName.length==0){
                        res.send('只支持png和jpg格式图片');
                        return;
                }else{
                        form.uploadDir="../public/images/";
                        form.keepExtensions=true;
                        form.maxFieldsSize=2*1024;
                        var avatarName=Math.random()+'.'+extName;
                        var newPath=form.uploadDir+avatarName;

                        console.log('这个是'+newPath);
                        console.log("old"+files.fileImage01.path);

                        console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');

                        console.log('第一个'+files.fileImage01.path);
                        console.log('第二个'+newPath);

                        fs.renameSync(files.fileImage01.path,newPath);
                        res.locals.success='上传成功....';
                        console.log('add img ---end');
                }
                console.log("得到的借股票"+JSON.stringify(fields)+avatarName);
                articleDAO.add(fields.title,fields.content,avatarName,req,res,function(result){
                        if(result.affectedRows==1){
                                res.send({"res":"1"});
                        }else{
                                res.json({"res":"0"});
                        }
                })
        });

});
module.exports = router;